<template>
  <div class="app-container">
    <div
      class="header"
      style="display: flex; justify-content: space-between"
    >
      <el-form
        :model="queryParams"
        ref="queryRef"
        :inline="true"
        v-show="showSearch"
      >
        <el-form-item>
          <el-button
            icon="refresh"
            color=" rgb(69, 76, 105)"
            style="color: #fff"
            @click="resetQuery()"
          />
        </el-form-item>
        <el-form-item>
          <el-button
            @click="handleAdd"
            v-hasPermi="['system:car:add']"
            style="padding: 0 20px"
          >
            新 增
          </el-button>
        </el-form-item>
        <el-form-item>
          <el-button
            @click="handleImport"
            color="rgb(51, 153, 102)"
            style="color: #fff; padding: 0 20px"
            v-hasPermi="['system:car:import']"
          >
            导 入
          </el-button>
        </el-form-item>
      </el-form>
      <el-form
        :model="queryParams"
        ref="queryRef"
        :inline="true"
        v-show="showSearch"
      >
        <el-form-item
          label=""
          prop="brandName"
        >
          <el-input
            v-model="queryParams.brandName"
            placeholder="请输入品牌名称"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item
          label=""
          prop="品牌型号"
        >
          <el-input
            v-model="queryParams.brandModel"
            placeholder="请输入品牌型号"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <!-- <el-form-item
          label=""
          prop="createTime"
        >
          <el-date-picker
            clearable
            v-model="queryParams.createTime"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择时间-时间"
          >
          </el-date-picker>
        </el-form-item> -->

        <!-- 加入的 -->
        <el-form-item
          label=""
          prop="createTime"
        >
          <el-date-picker
            clearable
            v-model="createTime"
            type="datetimerange"
            value-format="YYYY-MM-DD HH:mm:ss"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            @keyup.enter="handleQuery"
          >
          </el-date-picker>
        </el-form-item>

        <el-form-item>
          <el-button
            type="info"
            icon="Search"
            @click="handleQuery()"
          />
        </el-form-item>
      </el-form>
    </div>

    <el-table
      v-loading="loading"
      :data="carList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column
        label="品牌图标"
        align="center"
        prop="brandImg"
      >
        <template #default="scope">
          <el-image
            style="width: 100px; height: 100px"
            :src="scope.row.brandImg"
            fit="contain"
          >
          </el-image>
        </template>
      </el-table-column>
      <el-table-column
        label="品牌名称"
        align="center"
        prop="brandName"
      />
      <el-table-column
        label="品牌型号"
        align="center"
        prop="brandModel"
      />
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        width="180"
      >
        <template #default="scope">
          <span>{{
            parseTime(scope.row.createTime, "{y}-{m}-{d} {h}:{i}:{s}")
          }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <el-button
            link
            type="primary"
            icon="Edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:car:edit']"
            >编辑</el-button
          >
          <el-button
            link
            type="primary"
            icon="Delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:car:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改车辆管理对话框 -->
    <el-dialog
      :title="title"
      v-model="open"
      width="500px"
      append-to-body
      :before-close="cancel"
    >
      <el-form
        ref="carRef"
        :model="form"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item
          label="品牌图标"
          prop="brandImg"
        >
          <el-upload
            class="brandIcon"
            action="#"
            :show-file-list="false"
            :auto-upload="false"
            :on-change="handleIcon"
          >
            <img
              v-if="previewIcon"
              :src="previewIcon"
              object-fit="contain"
              class="previewIcon"
            >
            </img>
            <el-icon
              v-else
              class="uploaderIcon"
              ><Plus
            /></el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item
          label="品牌名称"
          prop="brandName"
        >
          <el-input
            v-model="form.brandName"
            placeholder="请输入品牌名称"
          />
        </el-form-item>
        <el-form-item
          label="品牌型号"
          prop="brandModel"
        >
          <el-input
            v-model="form.brandModel"
            placeholder="请输入品牌型号"
          />
        </el-form-item>
         <el-form-item
          label="是否推荐"
          prop="isRecommend"
        >
        <el-radio-group v-model="form.isRecommend">
          <el-radio :label="1">是</el-radio>
          <el-radio :label="0">否</el-radio>
        </el-radio-group>
      </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button
            type="primary"
            @click="submitForm"
            >确 定</el-button
          >
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Car">
import { listCar, getCar, delCar, addCar, updateCar } from "@/api/system/car";

const { proxy } = getCurrentInstance();

const carList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const previewIcon = ref("");

//存储时间搜索时的时间参数
const createTime = ref("");

const data = reactive({
  file:null,
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    brandName: null,
    brandModel: null,
    createTime: null,
  },
  rules: {},
});

const { queryParams, form, rules } = toRefs(data);

/** 查询车辆管理列表 */
function getList() {
  loading.value = true;
  console.log(queryParams.value,'条件查询传递的的参数gggggggggggggg')
  listCar(queryParams.value).then((response) => {
    console.log(response,'条件查询返回的列表数据')
    carList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  data.file=null;
  previewIcon.value = null;
  open.value = false;
  form.value = {};
  done();
}

// 表单重置
function reset() {
  form.value = {
    carId: null,
    brandImg: null,
    brandName: null,
    brandModel: null,
    createTime: null,
    updateTime: null,
  };
  proxy.resetForm("carRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  console.log(createTime.value,'查询参数,点击搜索按钮时传递的参数')
  console.log(typeof createTime.value[0],'时间搜索时传递的时间参数')
  if(createTime.value.length == 2 && createTime.value){
    queryParams.value.startSift = createTime.value[0];
    queryParams.value.endSift = createTime.value[1];
  }else{
    queryParams.value.startSift = "";
    queryParams.value.endSift = "";
  }
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.carId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加车辆管理";
}

function handleImport() {

}

function handleIcon(param) {
  var reader = new FileReader();
  reader.onload = (e) => {
    previewIcon.value = e.target.result;
  };
  reader.readAsDataURL(param.raw);
  const lastDotIndex = param.raw.name.lastIndexOf(".");
  if (lastDotIndex > 0 && lastDotIndex < param.raw.name.length - 1) {
    const extension = param.raw.name.substring(lastDotIndex + 1);
    if (extension === "jpg" || extension === "png") {
      data.file = param.raw;
    } else {
      proxy.$message.error("文件名不合法！");
    }
  }
}

/** 修改按钮操作 */
function handleUpdate(row) {
  form.value = row;
  previewIcon.value = row.brandImg;
  open.value = true;
  title.value = "修改车辆管理";
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["carRef"].validate((valid) => {
    const formData = new FormData();
    formData.append("brandModel", form.value.brandModel);
    formData.append("brandName", form.value.brandName);
    if (data.file) {
      console.log(data.file);
      formData.append("file", data.file);
    }
   for (let pair of formData.entries()) {
  console.log(pair[0] + ', ' + pair[1]);
}
    if (valid) {
      if (form.value.carId != null) {
        updateCar(formData).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addCar(formData).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          data.file=null;
          previewIcon.value = null;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  console.log(row,'要删除当前行')
  const _carIds = row.carId || ids.value;
  proxy.$modal
    .confirm('是否确认删除车辆管理编号为"' + _carIds + '"的数据项？')
    .then(function () {
      return delCar(_carIds);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    "system/car/export",
    {
      ...queryParams.value,
    },
    `car_${new Date().getTime()}.xlsx`
  );
}

getList();
</script>

<style>
.brandIcon {
  border: 1px dotted rgb(150, 150, 150);
  border-radius: 6px;
  .uploaderIcon {
    font-size: 25px;
    color: #8c939d;
    text-align: center;
    width: 125px;
    height: 125px;
  }
  .previewIcon{
    width: 125px;
    height: 125px;
    object-fit: contain;
  }
}
.brandIcon:hover {
  border: 1px dotted cornflowerblue;
  .uploaderIcon {
    color: cornflowerblue;
  }
}
</style>
